﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpenseSystem.Model;
using ExpenseSystem.Lor;
using ExpenseSystem.Common;
using ExpenseSystem.DataUpdater;
using ExpenseSystem.Fether;
using ExpenseSystem.DataUpdater.Validation;

namespace ExpenseSystem.Core.OrderModules
{
    public class OrderTypeUpdaterRegister
    {
        int rows;
        public NormalDataUpdater<OrderTypeModel> GetOrderTypeUpdater()
        {
            NormalDataUpdater<OrderTypeModel> systemDataUpdater = new NormalDataUpdater<OrderTypeModel>();
            systemDataUpdater.DataUpdating += DataNotSpaceValid;
            systemDataUpdater.DataUpdating += SingletonValid;
            systemDataUpdater.DataDeleting += CheckAvaliable;
            return systemDataUpdater;
        }
        private void CheckAvaliable(object sender, DataValidationEventArgs<OrderTypeModel> e)
        {
            OrderFetcher orderFetcher = new OrderFetcher();
            var orders = orderFetcher.ListByType(e.Delete.Site, e.Delete.AutoId, out string message, out rows);
            if (orders.Count>0)
            {
                e.Cancle = true;
                e.Message = String.Format("[{0}]正在生效，不能删除", e.Delete.Name);
            }
        }

        private void SingletonValid(object sender, DataValidationEventArgs<OrderTypeModel> e)
        {
            OrderTypeFetcher orderTypeFetcher = new OrderTypeFetcher();
            string message = "";
            OrderTypeModel orderType = orderTypeFetcher.GetByCode(e.Insert.Site,e.Insert.Code, out message);
            if (orderType != null && orderType.AutoId != e.Insert.AutoId)
            {
                e.Cancle = true;
                message = String.Format("代号[{0}]已被[{1}]占用", orderType.Code, orderType.Name);
                return;
            }
        }

        private void DataNotSpaceValid(object sender, DataValidationEventArgs<OrderTypeModel> e)
        {
            if (String.IsNullOrWhiteSpace(e.Insert.Code))
            {
                e.Message = "代号不能为空";
                e.Cancle = true;
                return;
            }
            if (String.IsNullOrWhiteSpace(e.Insert.Name))
            {
                e.Message = "名称不能为空";
                e.Cancle = true;
                return;
            }
        }
    }
}
